/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.aspectj.annotation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.reflect.PerClauseKind;

import org.springframework.aop.Advisor;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Helper for retrieving @AspectJ beans from a BeanFactory and building
 * Spring Advisors based on them, for use with auto-proxying.
 *
 * @author Juergen Hoeller
 * @since 2.0.2
 * @see AnnotationAwareAspectJAutoProxyCreator
 */
public class BeanFactoryAspectJAdvisorsBuilder {

	private final ListableBeanFactory beanFactory;

	private final AspectJAdvisorFactory advisorFactory;

	@Nullable
	private volatile List<String> aspectBeanNames;

	private final Map<String, List<Advisor>> advisorsCache = new ConcurrentHashMap<>();

	private final Map<String, MetadataAwareAspectInstanceFactory> aspectFactoryCache = new ConcurrentHashMap<>();


	/**
	 * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory.
	 * @param beanFactory the ListableBeanFactory to scan
	 */
	public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory) {
		this(beanFactory, new ReflectiveAspectJAdvisorFactory(beanFactory));
	}

	/**
	 * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory.
	 * @param beanFactory the ListableBeanFactory to scan
	 * @param advisorFactory the AspectJAdvisorFactory to build each Advisor with
	 */
	public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
		Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
		Assert.notNull(advisorFactory, "AspectJAdvisorFactory must not be null");
		this.beanFactory = beanFactory;
		this.advisorFactory = advisorFactory;
	}



	public List<Advisor> buildAspectJAdvisors() {
		//获取缓存的引用
		List<String> aspectNames = this.aspectBeanNames;
		//表示这是第一次进来
		if (aspectNames == null) {
			synchronized (this) {
				aspectNames = this.aspectBeanNames;
				//条件成立 说明缓存是空的
				if (aspectNames == null) {
					//创建一个增强器列表 ，保存通过 @Aspectj 注解定义的 切面
					List<Advisor> advisors = new ArrayList<>();
					//从这里其实就可以看出来，缓存存的就是有  @Aspectj 注解 的  beanName
					aspectNames = new ArrayList<>();
					//拿到bf内全部的beanName
					String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
							this.beanFactory, Object.class, true, false);
					//循环遍历
					for (String beanName : beanNames) {
						//类型校验
						if (!isEligibleBean(beanName)) {
							continue;
						}
						// We must be careful not to instantiate beans eagerly as in this case they
						// would be cached by the Spring container but would not have been weaved.
						//判断bean类型是不是空  ，为空 的时候 就是一个抽象的模板bean
						Class<?> beanType = this.beanFactory.getType(beanName, false);
						if (beanType == null) {
							continue;
						}
						//判断当前bean类型或者他的祖宗类们是不是加了Aspect注解，这个方法其实依靠的就是一些注解的使用，没啥营养
						//条件成立，说明当前类是一个切面
						if (this.advisorFactory.isAspect(beanType)) {
							//加入到切面集合
							aspectNames.add(beanName);
							//构建一个切面元数据
							AspectMetadata amd = new AspectMetadata(beanType, beanName);
							//正常情况下，ajType都是 单实例的，其他情况不考虑了，属于花里花哨玩法
							if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
								//使用工厂模式管理Aspect元数据 关联的 真实 @Aspect 注解的实例对象
								MetadataAwareAspectInstanceFactory factory =
										new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
								//获取所有加了 aspect 注解的实例
								//这个方法返回了 添加 @Aspect 注解的class相关的Advisor信息 ， step into
								List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
								//如果当前bean是单实例的 ，做一个缓存映射
								if (this.beanFactory.isSingleton(beanName)) {
									this.advisorsCache.put(beanName, classAdvisors);
								}
								else {
									//否则  映射的缓存是  bean名字   工厂
									this.aspectFactoryCache.put(beanName, factory);
								}
								advisors.addAll(classAdvisors);
							}
							else {
								// Per target or per this.
								if (this.beanFactory.isSingleton(beanName)) {
									throw new IllegalArgumentException("Bean with name '" + beanName +
											"' is a singleton, but aspect instantiation model is not singleton");
								}
								MetadataAwareAspectInstanceFactory factory =
										new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
								this.aspectFactoryCache.put(beanName, factory);
								advisors.addAll(this.advisorFactory.getAdvisors(factory));
							}
						}
					}
					//将刚刚for循环处理的打了@Aspect注解的beanName 缓存起来，表示 提取 切面操作做完了
					this.aspectBeanNames = aspectNames;
					return advisors;
				}
			}
		}
		//如果确实为空，那就返回空集合
		if (aspectNames.isEmpty()) {
			return Collections.emptyList();
		}
		//提取缓存的advisor，返回
		List<Advisor> advisors = new ArrayList<>();
		for (String aspectName : aspectNames) {
			List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
			if (cachedAdvisors != null) {
				advisors.addAll(cachedAdvisors);
			}
			else {
				MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
				advisors.addAll(this.advisorFactory.getAdvisors(factory));
			}
		}
		return advisors;
	}

	/**
	 * Return whether the aspect bean with the given name is eligible.
	 * @param beanName the name of the aspect bean
	 * @return whether the bean is eligible
	 */
	protected boolean isEligibleBean(String beanName) {
		return true;
	}

}
